package edu.fivegroup.mall.goods;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/updateGoods")
public class EditGoodsHandler extends HttpServlet {
    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 处理中文参数
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端参数
        String gid = request.getParameter("id");
        String title = request.getParameter("title");
        String priceStr = request.getParameter("price");
        String descr = request.getParameter("descr");
        String img = request.getParameter("img");
        String midStr = request.getParameter("mid");

        try {
            // 转换数据类型
            BigDecimal price = new BigDecimal(priceStr);
            int mid = Integer.parseInt(midStr);

            int id = Integer.parseInt(gid);
            // 创建Goods对象并设置属性
            Goods goods = new Goods();
            goods.setId(id);
            goods.setTitle(title);
            goods.setPrice(price);
            goods.setDescr(descr);
            goods.setImg(img);
            goods.setMid(mid);

            // 调用DAO层保存数据
            int result = goodsDao.updateGoods(goods);
            if (result == 1) {
                response.getWriter().write("success"); // 成功响应
            } else {
                response.getWriter().write("添加失败，数据库操作未成功");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("价格或商家ID格式错误");
            e.printStackTrace();
        } catch (Exception e) {
            response.getWriter().write("系统错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
